﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Collections;
using OS.BLL;
using Newtonsoft.Json;
using System.IO;
using System.Drawing.Imaging;

namespace DownloadPlug_ins
{
    public partial class SyncTool : Form
    {
        public Common2 common = new Common2();
        public static string url = "";

        public static int SyncType = 0;//下载图片 自动执行周期
        public static int SyncType2 = 0;//上传数据  自动执行周
        public Bll_jbxx_spdaH bllJbxx_spdaH = new Bll_jbxx_spdaH();
        public BackgroundWorker Consumer1 = new BackgroundWorker();
        public bool IsInit = false;//是否初始化
        public int pageSize = 20;//每页显示

        public static int Status = 0;//当状态为0 为等待，1 表示 正在执行任务
        public static int Status2 = 0;//当状态为0 为等待，1 表示 正在执行任务
        public SyncTool()
        {
            InitializeComponent();
            this.pSet.Cursor = Cursors.Hand;
            ConfigModel model = common.GetXml();//获取相关配置属性
            url = model.WebService;

            if (model.ServerType != "")
                SyncType = int.Parse(model.ServerType);

            if (model.ServerType2 != "")
                SyncType2 = int.Parse(model.ServerType2);
            Init();
            MyTimer();
        }

        private void MyTimer()
        {
            double spt = 1000*60*10;//每10分钟
            System.Timers.Timer MT = new System.Timers.Timer(spt);
            MT.Elapsed += new System.Timers.ElapsedEventHandler(MTimedEvent);
            MT.Enabled = true;
        }
        //构造 Timer实例   间隔时间事件  
        private void MTimedEvent(object source, System.Timers.ElapsedEventArgs e)
        {
            SptpModel model1 = new SptpModel();

            model1.TpPath = this.ctxtPath.Text;
            model1.TpUrl = this.cTextBox1.Text;

            if (!Consumer1.IsBusy)
            {
                this.osProgress2.AutoProgress = true;
                Consumer1.RunWorkerAsync(model1);
            }
              
        }

 
 

        private void gbtnSPDownLoad_Click(object sender, EventArgs e)
        {
            SptpModel model1 = new SptpModel();
            this.osProgress2.AutoProgress = true;
            model1.TpPath = this.ctxtPath.Text;
            model1.TpUrl = this.cTextBox1.Text;

            if (!Consumer1.IsBusy)
                Consumer1.RunWorkerAsync(model1);
        }
  

        /// <summary>
        /// 现实二进制流代表的图片
        /// </summary>
        /// <param name="imgBytesIn"></param>
        public bool ShowImgByByte(byte[] imgBytesIn, string imagePath)
        {
            bool isSuccess = false;
            try
            {
                MemoryStream ms = new MemoryStream(imgBytesIn);
                Bitmap bmp = new Bitmap(ms);
                bmp.Save(imagePath, ImageFormat.Jpeg);
                ms.Close();
                isSuccess = true;
            }
            catch (Exception ex)
            { }

            return isSuccess;
        }
        private void DownloadData(object sender, DoWorkEventArgs e)
        {
            SptpModel model1 = (SptpModel)e.Argument;//图片存储路径
            string path = model1.TpPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd");
            string url = model1.TpUrl + "\\" + DateTime.Now.ToString("yyyy-MM-dd");

          

            int pageNumber = 1;

            string strWhere = " (tpdz is null or tpdz='') and  DATALENGTH(tp) >10";
            int count = bllJbxx_spdaH.GetRecordCount(strWhere);

            if (count > pageSize)
            {
                int pageCount = count % pageSize > 0 ? count / pageSize + 1 : count / pageSize;
                for (int j = 2; j <= pageCount; j++)
                {
                    pageNumber = j;
                    int startIndex = (pageNumber - 1) * pageSize + 1;
                    int endIndex = pageNumber * pageSize;
                    List<jbxx_spdaH_Entity> ls = bllJbxx_spdaH.GetModelList(strWhere, "xgsj desc", startIndex, endIndex);

                    DownloadImg(ls, path, url);

                }
            }
            else
            {
                int startIndex = (pageNumber - 1) * pageSize + 1;
                int endIndex = pageNumber * pageSize;
                List<jbxx_spdaH_Entity> ls = bllJbxx_spdaH.GetModelList(strWhere, "xgsj desc", startIndex, endIndex);
                DownloadImg(ls, path, url);
            }

            Status = 0;//任务执行完后 进入等待
            if (count > 0)

                MessageBox.Show(" 下载完成！ 共计下载数据" + count + "条");

            else

                MessageBox.Show(" 本时间段未获取到数据，可能网络原因(请检查网络),或者可能是服务器端已停止服务(请检查Web地址是否能够正常访问)，请联系技术人员！");



            this.osProgress2.AutoProgress = false;
        }

        private void DownloadImg(List<jbxx_spdaH_Entity> ls, string path, string url)
        {
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            if (ls != null)
            {
                foreach (jbxx_spdaH_Entity e1 in ls)
                {
                    //图片有效
                    if (e1.tp.Length > 20)
                    {
                        string _path = path + "\\" + e1.spbh + ".jpg";
                        string _url = url + "\\" + e1.spbh + ".jpg";

                        if (ShowImgByByte(e1.tp, _path))
                        {
                            bllJbxx_spdaH.ExecuteSql("update jbxx_spdaH set  tpdz='" + _url + "' where DjLsh=" + e1.DjLsh);
                        }


                    }
                }
            }
        }
        private void Init()
        {
            if (!IsInit)
            {
                Consumer1.DoWork += new DoWorkEventHandler(DownloadData);

                IsInit = true;

            }
        }

 


  
        private void gbtnSet_Click(object sender, EventArgs e)
        {
            Config config = new Config();
            config.ShowDialog();
        }

        private void SyncTool_Load(object sender, EventArgs e)
        {
            this.notifyIcon1.ContextMenuStrip = contextMenuStrip1;
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            notifyIcon1.Visible = false;
            this.Show();
            WindowState = FormWindowState.Normal;
            this.Focus();
        }

        private void SyncTool_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)    //最小化到系统托盘
            {
                this.notifyIcon1.Visible = true;  //显示托盘图标
                this.Hide();    //隐藏窗口
            }
        }

        private void SyncTool_FormClosing(object sender, FormClosingEventArgs e)
        {
            //Application.Exit();
            //注意判断关闭事件Reason来源于窗体按钮，否则用菜单退出时无法退出!
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;    //取消"关闭窗口"事件
                this.WindowState = FormWindowState.Minimized;    //使关闭时窗口向右下角缩小的效果
                this.notifyIcon1.Visible = true;
                this.Hide();
                return;
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
            this.Show();
            WindowState = FormWindowState.Normal;
            this.Activate();
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            this.notifyIcon1.Visible = false;

            this.Close();

            this.Dispose();
            System.Environment.Exit(0);
        }

        private void gbtnQuery_Click(object sender, EventArgs e)
        {
            Picture picture = new Picture();
            picture.ShowDialog();
        }

        private void pSet_Click(object sender, EventArgs e)
        {
            Config config = new Config();
            config.ShowDialog();
        }
  
    }
}
